package cn.wfu.rlrjds.app.repairman.service.ipml;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.wfu.rlrjds.app.bean.RepairmanSearch;
import cn.wfu.rlrjds.app.bean.UserSearch;
import cn.wfu.rlrjds.app.repairman.dao.IRepairmanDao;
import cn.wfu.rlrjds.app.repairman.domain.Repaireman;
import cn.wfu.rlrjds.app.repairman.service.IRepairmanService;
import cn.wfu.rlrjds.app.user.dao.IUserDao;
import cn.wfu.rlrjds.app.user.domain.User;
import cn.wfu.rlrjds.app.user.service.ipml.UserEcxeption;
import cn.wfu.rlrjds.jersey.api.IMUserAPI;
import cn.wfu.rlrjds.jersey.comm.ClientContext;
import cn.wfu.rlrjds.jersey.comm.EasemobRestAPIFactory;
import cn.wfu.rlrjds.jersey.comm.body.IMUserBody;
import cn.wfu.rlrjds.jersey.comm.body.ModifyNicknameBody;
import cn.wfu.rlrjds.jersey.comm.body.ResetPasswordBody;
import cn.wfu.rlrjds.jersey.comm.wrapper.ResponseWrapper;
import cn.wfu.rlrjds.utils.EasemobRestAPIFactoryUtils;
import cn.wfu.rlrjds.utils.MD5Util;

@Service(value = "adminService")
@Transactional(readOnly = true)
public class RepairmanServiceIpml implements IRepairmanService {
	@Resource
	private IRepairmanDao repairmanDao;

	@Resource
	private IUserDao userDao;

	public void getAllAdmin() {
		List<Repaireman> allAdmin = repairmanDao.getAllRepairman();
		System.out.println(allAdmin);
	}

	/**
	 * 通过id查找用户
	 */
	@Override
	public Repaireman findRepairmanById(String id) throws RepairmanException {
		// TODO Auto-generated method stub
		Repaireman repairman = this.repairmanDao.findById(id);
		if (repairman != null) {
			throw new RepairmanException("学生端无法请求管理员账号");
		} else {
			return repairman;
		}
	}

	/**
	 * 查找所有管理员
	 */
	@Override
	public List<Repaireman> list(RepairmanSearch repairmanSearch) {
		// TODO Auto-generated method stub
		return repairmanDao.selectList("findListBy", repairmanSearch);
	}

	/**
	 * 保存管理员
	 */
	@Override
	@Transactional(isolation = Isolation.DEFAULT, readOnly = false, propagation = Propagation.REQUIRED, rollbackForClassName = {
			"RepairmanException", "RuntimeException" })
	public void saveRepairman(Repaireman form) throws RepairmanException {
		// TODO Auto-generated method stub
		Repaireman repairman = this.repairmanDao.findById(form.getId());
		User _user = this.userDao.findById(form.getId());
		if (repairman != null || _user != null) {
			throw new RepairmanException("您注册的用户名已经存在");
		} else {
			// 注册成为IMUser用户
			IMUserAPI imuser = (IMUserAPI) EasemobRestAPIFactoryUtils
					.getIMUserAPI();
			// 创建环信IMUser用户
			IMUserBody userBody = new IMUserBody(form.getId(),
					form.getPassword(), form.getNickName());
			ResponseWrapper responseWrapper = (ResponseWrapper) imuser
					.createNewIMUserSingle(userBody);
			// 设置注册日期
			form.setRegist_time(new Date());
			// 使用md5对密码进行加密
			String password = form.getPassword();
			form.setPassword(MD5Util.getkeyBeanofStr(password));
			// 设置管理员未登录状态
			form.setIslogin(0);
			// 保存用户
			this.repairmanDao.save(form);

			if (200 != responseWrapper.getResponseStatus()) {
				throw new RepairmanException("向环信中添加用户失败");
			}
		}
	}

	/**
	 * 删除维修员
	 * 
	 * @throws RepairmanException
	 */
	@Override
	@Transactional(isolation = Isolation.DEFAULT, readOnly = false, propagation = Propagation.REQUIRED, rollbackForClassName = {
			"RepairmanException", "RuntimeException" })
	public void deleteRepairman(String[] ids) throws RepairmanException {
		// TODO Auto-generated method stub
		EasemobRestAPIFactory factory = ClientContext.getInstance()
				.init(ClientContext.INIT_FROM_PROPERTIES).getAPIFactory();

		IMUserAPI imuser = (IMUserAPI) factory
				.newInstance(EasemobRestAPIFactory.USER_CLASS);
		for (int i = 0; i < ids.length; i++) {
			// 删除环信IMUser
			ResponseWrapper responseWrapper = (ResponseWrapper) imuser
					.deleteIMUserByUserName(ids[i]);
			this.repairmanDao.deleteByIdDeleteStatus(ids[i]);
			if (200 != responseWrapper.getResponseStatus()) {
				// 删除本地数据库
				throw new RepairmanException("删除维修员失败");
			}
		}
	}

	/**
	 * 查找所有维修员
	 */
	@Override
	public List<Repaireman> list() {
		// TODO Auto-generated method stub
		return this.list(new RepairmanSearch());
	}

	/**
	 * 获取在线维修员
	 */
	@Override
	public List<Repaireman> getRepairmansByStatus() {
		// TODO Auto-generated method stub
		return this.repairmanDao.getRepairmansByStatus();
	}

	/**
	 * 用户登陆
	 */
	@Override
	@Transactional(isolation = Isolation.DEFAULT, readOnly = false, propagation = Propagation.REQUIRED, rollbackForClassName = {
			"RepairmanException", "RuntimeException" })
	public Repaireman login(String id) throws RepairmanException {
		// TODO Auto-generated method stub
		Repaireman repaireman = this.repairmanDao.findById(id);
		if (null == repaireman) {
			throw new RepairmanException("用户名不存在");
		} else {
			Map<String, String> map = new HashMap<String, String>();
			map.put("id", id);
			map.put("status", "1");
			this.repairmanDao.updateRepairemanIsLogin(map);
			return repaireman;
		}
	}

	/**
	 * 修改维修员密码
	 * 
	 * @throws RepairmanException
	 * 
	 * @throws UserEcxeption
	 */
	@Override
	@Transactional(isolation = Isolation.DEFAULT, readOnly = false, propagation = Propagation.REQUIRED, rollbackForClassName = {
			"UserEcxeption", "RuntimeException" })
	public void updateRepairmanPassword(Repaireman repaireman, String newpass)
			throws RepairmanException {
		// TODO Auto-generated method stub
		if (StringUtils.isBlank(newpass)) {
			throw new RuntimeException("新密码不能为空");
		}
		Repaireman _repaireman = this.repairmanDao.findById(repaireman.getId());
		if (_repaireman != null) {
			if (!_repaireman.getPassword().equals(
					MD5Util.getkeyBeanofStr(repaireman.getPassword()))) {
				throw new RepairmanException("输入的旧密码不正确");
			} else {
				// 设置新密码
				repaireman.setPassword(MD5Util.getkeyBeanofStr(newpass));
				// 修改环信端密码
				IMUserAPI imUserAPI = EasemobRestAPIFactoryUtils.getIMUserAPI();
				ResetPasswordBody resetPasswordBody = new ResetPasswordBody(
						newpass);
				this.repairmanDao.updateRepairmanPassword(repaireman);
				ResponseWrapper responseWrapper = (ResponseWrapper) imUserAPI
						.modifyIMUserPasswordWithAdminToken(repaireman.getId(),
								resetPasswordBody);
				if (200 != responseWrapper.getResponseStatus()) {
					throw new RepairmanException("环信端修改数据失败");
				}
			}
		} else {
			throw new RuntimeException("查找的维修员为空");
		}

	}

	/**
	 * 修改维修员资料
	 * 
	 * @return 修改后的个人资料
	 * @throws RepairmanException
	 * @throws UserEcxeption
	 */
	@Transactional(isolation = Isolation.DEFAULT, readOnly = false, propagation = Propagation.REQUIRED, rollbackForClassName = {
			"UserEcxeption", "RuntimeException" })
	public Repaireman updateRepairemanInfo(Repaireman repaireman, String saveDir)
			throws RepairmanException {
		// TODO Auto-generated method stub
		Repaireman _repaireman = this.repairmanDao.findById(repaireman.getId());
		// 删除本地文件
		if (StringUtils.isNotBlank(repaireman.getAvatarUrl())) {
			if (StringUtils.isNotBlank(_repaireman.getAvatarUrl())
					&& !repaireman.getAvatarUrl().equals(
							_repaireman.getAvatarUrl())) {
				String AvatarUrl = _repaireman.getAvatarUrl();
				File file = new File(saveDir, AvatarUrl);
				if (file.exists()) {
					file.delete();
				}
			}
		}
		// 修改用户数据库信息
		if (!repaireman.equals(_repaireman)) {
			this.repairmanDao.updateUserInfo(repaireman);
		} else {
			return _repaireman;
		}
		// 修改维修记录用户信息
		// 修改环信端昵称
		ResponseWrapper responseWrapper = null;
		if (!repaireman.getNickName().equals(_repaireman.getNickName())) {
			IMUserAPI imUserAPI = EasemobRestAPIFactoryUtils.getIMUserAPI();
			ModifyNicknameBody modifyNicknameBody = new ModifyNicknameBody(
					repaireman.getNickName());
			responseWrapper = (ResponseWrapper) imUserAPI
					.modifyIMUserNickNameWithAdminToken(repaireman.getId(),
							modifyNicknameBody);
			if (200 == responseWrapper.getResponseStatus()) {
				return this.repairmanDao.findById(repaireman.getId());
			} else {
				throw new RepairmanException("环信端密码修改错误");
			}
		} else {
			return this.repairmanDao.findById(repaireman.getId());
		}
	}

	/**
	 * 用户退出
	 * 
	 * @throws RepairmanException
	 */
	@Override
	@Transactional(isolation = Isolation.DEFAULT, readOnly = false, propagation = Propagation.REQUIRED, rollbackForClassName = {
			"RepairmanException", "RuntimeException" })
	public void logout(String id) throws RepairmanException {
		// TODO Auto-generated method stub
		Repaireman repaireman = this.repairmanDao.findById(id);
		if (null == repaireman) {
			throw new RepairmanException("用户名不存在");
		} else {
			Map<String, String> map = new HashMap<String, String>();
			map.put("id", id);
			map.put("status", "0");
			this.repairmanDao.updateRepairemanIsLogin(map);
		}
	}

	@Override
	@Transactional(isolation = Isolation.DEFAULT, readOnly = false, propagation = Propagation.REQUIRED, rollbackForClassName = {
			"RepairmanException", "RuntimeException" })
	public void updatePasswordNoValidate(Repaireman form)
			throws RepairmanException {
		// TODO Auto-generated method stub
		Repaireman repaireman = this.repairmanDao.findById(form.getId());

		if (!form.getPassword().equals(repaireman.getPassword())) {
			form.setPassword(MD5Util.getkeyBeanofStr(form.getPassword()));
			// 修改环信端密码
			IMUserAPI imUserAPI = EasemobRestAPIFactoryUtils.getIMUserAPI();
			ResetPasswordBody resetPasswordBody = new ResetPasswordBody(
					form.getPassword());
			this.repairmanDao.updateRepairmanPassword(form);
			ResponseWrapper responseWrapper = (ResponseWrapper) imUserAPI
					.modifyIMUserPasswordWithAdminToken(form.getId(),
							resetPasswordBody);
			if (200 != responseWrapper.getResponseStatus()) {
				throw new RepairmanException("环信端修改数据失败");
			}
		}
	}
}
